<template>
  <div ref="tabRef" flex h-full pr-18 items-end>
    <page-tab
      v-for="item in tabStore.tabs"
      :key="item.path"
      mode="chrome"
      :dark-mode="appStore.isDark"
      :active="tabStore.activeTabPath === item.path"
      :active-color="naiveThemeOverrides.common.primaryColor"
      :closable="item.name != tabStore.homeTab!.name"
      @click="tabStore.handleClickTab(item.path)"
      @close="tabStore.removeTab(item.path)"
      @contextmenu="handleContextMenu($event, item)"
    >
      <template #prefix>
        <icon
          :icon="(item.meta.icon as string)"
          class="inline-block align-text-bottom text-16"
        />
      </template>
      {{ item.meta.title }}
    </page-tab>
  </div>
  <context-menu
    :visible="dropdown.visible"
    :current-path="dropdown.currentPath"
    :x="dropdown.x"
    :y="dropdown.y"
    @update:visible="handleDropdownVisible"
  />
</template>

<script lang="ts" setup>
import { Icon } from "@iconify/vue";
import { PageTab } from "@soybeanjs/vue-materials";
import { useTabStore, useAppStore } from "@/store";
import { ContextMenu } from "./components";
import { naiveThemeOverrides } from "~/setting";
import { TabRoute } from "@/store";

interface Emits {
  (e: "scroll", clientX: number): void;
}

const emit = defineEmits<Emits>();
const tabStore = useTabStore();
const appStore = useAppStore();

// 获取当前激活的tab的clientX
const tabRef = ref<HTMLElement>();
const getActiveTabClientX = async () => {
  await nextTick();
  if (
    tabRef.value &&
    tabRef.value.children.length &&
    tabRef.value.children[tabStore.activeTabIndex]
  ) {
    const activeTabElement = tabRef.value.children[tabStore.activeTabIndex];
    const { x, width } = activeTabElement.getBoundingClientRect();
    const clientX = x + width / 2;
    setTimeout(() => {
      emit("scroll", clientX);
    }, 50);
  }
};

interface DropdownConfig {
  visible: boolean;
  x: number;
  y: number;
  currentPath: string;
}

const dropdown = ref<DropdownConfig>({
  visible: false,
  x: 0,
  y: 0,
  currentPath: "",
});

const setDropdown = (config: Partial<DropdownConfig>) => {
  Object.assign(dropdown.value, config);
};

let isClickContextMenu = false;

function handleDropdownVisible(visible: boolean) {
  if (!isClickContextMenu) {
    setDropdown({ visible });
  }
}

/** 点击右键菜单 */
const handleContextMenu = async (e: MouseEvent, tab: TabRoute) => {
  e.preventDefault();

  const { clientX, clientY } = e;

  isClickContextMenu = true;

  const DURATION = dropdown.value.visible ? 150 : 0;

  setDropdown({ visible: false });

  setTimeout(() => {
    setDropdown({
      visible: true,
      x: clientX,
      y: clientY,
      currentPath: tab.path,
    });

    isClickContextMenu = false;
  }, DURATION);
};

watch(
  () => tabStore.activeTabIndex,
  () => getActiveTabClientX(),
  { immediate: true }
);
</script>
